<template>
    <div class="map-container">
        <!-- 可以删除对应的代码-->
        <div class="map-title">
            <div v-if="back" id="back" @click="showAllMap" style="cursor: pointer;">返回</div>
        </div>
        <div id="map"></div>
    </div>
</template>

<script>
import {reactive, onMounted} from 'vue';
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
    setup() {
        const state = reactive({
            map: null,
            AMap: null,
            back: false,
            polygons: [],
            district: null,
            polygon: null,
            options: { //定义的path待研究
                hideWithoutStyle: true,//是否隐藏设定区域外的楼块
                areas: [{ //围栏1
                    // visible:false,//是否可见
                    rejectTexture: true,//是否屏蔽自定义地图的纹理
                    color1: 'ffffff00',//楼顶颜色
                    color2: 'ffffcc00',//楼面颜色
                    path: [[120.427083, 36.134563], [120.429336, 36.134896],
                        [120.429921, 36.133197], [120.427637, 36.132839]
                    ]
                }]
            }
        });

// 初始化遮罩
        const initArea = async (city, isChildDraw = false) => {
            state.district.search(city, function (status, result) {
                // 外多边形坐标数组和内多边形坐标数组
                var outer = [
                    new state.AMap.LngLat(-360, 90, true),
                    new state.AMap.LngLat(-360, -90, true),
                    new state.AMap.LngLat(360, -90, true),
                    new state.AMap.LngLat(360, 90, true),
                ];
                console.log(result);

                // 绘制遮罩
                var holes = result.districtList[0].boundaries;
                var pathArray = [outer];
                pathArray.push.apply(pathArray, holes);
                state.polygon = new state.AMap.Polygon({
                    pathL: pathArray,
                    strokeColor: "#00eeff",
                    strokeWeight: 1,
                    fillColor: "#020933",
                    fillOpacity: 1,
                });
                state.polygon.setPath(pathArray);
                state.map.add(state.polygon);
                // 判断是否要绘制子区域
                if (isChildDraw) {
                    // 将搜索层级设置为 区、县
                    state.district.setLevel("district");
                    for (let i = 0; i < result.districtList[0].districtList.length; i++) {
                        areaPolyline(result.districtList[0].districtList[i].adcode);
                    }
                }
            });

        };

// 绘制区域描边
        const areaPolyline = (adcode) => {
            // 地图操作逻辑
            if (state.polygons.length) {
                state.map.remove(state.polygons);
                state.polygons = [];
            }
            state.district.search(adcode, function (status, result) {
                console.log("区", result);
                //   绘制区域描边
                let bounds = result.districtList[0].boundaries;
                for (let i = 0; i < bounds.length; i++) {
                    const polygon = new state.AMap.Polygon({
                        path: bounds[i],
                        strokeColor: "#784eda",
                        strokeWeight: 4,
                        fillColor: "#784eda",
                        fillOpacity: 0,
                    });
                    // 添加监听事件
                    polygon.on("mouseover", () => {
                        if (!state.back) {
                            polygon.setOptions({
                                fillOpacity: 0.7,
                            });
                        }
                    });
                    // 添加点击事件
                    polygon.on("click", () => {
                        // 判断是否为市级
                        if (!state.back) {
                            // 显示返回按钮
                            state.back = true;
                            state.map.setZoom(12);
                            // 修改中心位置为区级中心
                            state.map.setCenter([
                                result.districtList[0].center.lng,
                                result.districtList[0].center.lat,
                            ]);
                            //   绘画
                            initArea(result.districtList[0].adcode, false);
                        }
                    });
                    polygon.on("mouseout", () => {
                        polygon.setOptions({
                            fillOpacity: 0,
                        });
                    });
                    state.polygons.push(polygon);
                }
                state.map.add(state.polygons);
            });

        };

// 地图初始化
        const ininMap = async () => {
            // 配置安全设置
            window._AMapSecurityConfig = {
                securityJsCode: "4144f501ccd2073088e8c752730e60a8",
            };

            try {
                state.AMap = await AMapLoader.load({
                    key: "4144f501ccd2073088e8c752730e60a8",
                    version: "2.0",
                    plugins: [
                        "AMap.ToolBar",
                        "AMap.Driving",
                        "AMap.Polygon",
                        "AMap.DistrictSearch",
                        "AMap.Object3DLayer",
                        "AMap.Object3D",
                        "AMap.Polyline",
                        "AMap.CanvasLayer"
                    ],
                    Loca: {
                        // 是否加载 Loca， 缺省不加载
                        version: "2.0.0", // Loca 版本，缺省 1.3.2
                    },
                    complete: function(AMap) {
                        // AMap 现在被定义了，可以在这里使用 AMap 创建地图实例
                        state.map = new state.AMap.Map("map", {
                            center: [120.427276, 36.134148],
                            disableSocket: true,
                            viewMode: '2D',
                            // 其他配置...
                            pitch: 40,
                            zoom: 19,
                            layers: [
                                new state.AMap.TileLayer.RoadNet({
                                    // 其他配置...
                                }),

                            ]
                        });
                        // 在地图加载完成后添加事件监听器
                        AMap.event.addListenerOnce( state.map, 'complete', function() {
                            // 地图加载完成，可以在这里添加多边形等覆盖物
                            // 创建多边形覆盖物
                            const polygon = new state.AMap.Polygon({
                                path: [[120.427083,36.134563], [120.429336,36.134896],
                                    [120.429921,36.133197],[120.427637,36.132839]],
                                bubble: true,
                                fillOpacity: 0.6,
                                strokeWeight: 2,
                                strokeColor: '#00eeff',
                                fillColor: '#71B3ff',
                                map:  state.map
                            });

                            // 将多边形添加到地图
                            state.AMap.add(polygon);

                            // 调整视野以包含覆盖物
                            // state.AMap.setFitView([polygon]);

                            // 获取多边形的边界
                            var bounds = polygon.getBounds();
                            console.log(bounds, 'bounds');

                            // 如果需要实现多边形以外的区域镂空，可能需要使用其他技术或插件
                            // 例如，您可以使用 CanvasLayer 来绘制一个遮罩层
                            // 以下是一个使用 CanvasLayer 的示例代码
                            var canvasLayer = new AMap.CanvasLayer({
                                map: state.map,
                                bounds: bounds,
                                zooms: [3, 18], // 适用的缩放级别范围
                            });

                            // 绘制函数
                            canvasLayer.draw = function(param) {
                                var ctx = param.ctx;
                                var bounds = param.bounds;
                                var path = polygon.getPath(); // 获取多边形的路径

                                // 清除画布
                                // ctx.clearRect(0, 0, canvas.width, canvas.height);

                                // 绘制遮罩层
                                ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'; // 遮罩层的颜色和透明度
                                ctx.beginPath();
                                ctx.rect(bounds.minX, bounds.minY, bounds.maxX - bounds.minX, bounds.maxY - bounds.minY);
                                ctx.closePath();
                                ctx.fill();

                                // 绘制多边形路径
                                ctx.beginPath();
                                for (var i = 0, len = path.length; i < len; i++) {
                                    var point = path[i];
                                    ctx.lineTo(point[0], point[1]);
                                }
                                ctx.closePath();
                                ctx.fill();
                            };

                            // 将 CanvasLayer 添加到地图
                            canvasLayer.setMap(state.AMap);
                        });
                    }
                });



                state.district = new state.AMap.DistrictSearch({
                    subdistrict: 3,
                    extensions: "all",
                    level: "city",
                });

                // 调用 initArea 函数，传入需要的参数
                // await initArea("厦门市", true);
                // 初始化地图
                // 绘制路径
                // 确保地图加载完成后再添加多边形


            } catch (e) {
                console.error(e);
            }
        };
        // 显示总览
        const showAllMap = () => {
            state.back = false;
            if (state.polygon) {
                // 清除遮罩
                state.map.remove(state.polygon);
            }
            initArea("厦门市", true);
            state.map.setCenter([118.113994, 24.614998]);
            state.map.setZoom(11);
        }
        onMounted(async () => {
            await ininMap();
        });


        return {
            ...state,
            initArea,
            areaPolyline,
            showAllMap,

        };
    }
}
</script>

<style>
.map-container {
    width: 100%;
    height: 100%;
}

#map {
    height: 100%;
    width: 100%;
}
</style>
